package cn.labelnet.android.roomdb.user.adapter

import android.support.v7.widget.AppCompatTextView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.labelnet.android.roomdb.R
import cn.labelnet.android.roomdb.base.data.tables.UserTable
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by yuan on 03/08/2017.
 * all user
 */

class UserListAdapter constructor(onUserListListener: OnUserListListener) : RecyclerView.Adapter<UserListAdapter.UserListViewHolder>() {

    private var userList = ArrayList<UserTable>()
    private var onUserListListener: OnUserListListener = onUserListListener

    /**
     * add tables
     */
    fun addUsers(datas: List<UserTable>) {
        if (datas.isNotEmpty()) {
            this.userList.addAll(datas)
            this.notifyItemRangeInserted(itemCount - datas.size, datas.size)
        }
    }

    /**
     * clear table
     */
    fun clearUsers() {
        if (this.userList.isNotEmpty()) {
            this.userList.clear()
            this.notifyDataSetChanged()
        }
    }

    override fun onBindViewHolder(holder: UserListViewHolder?, position: Int) {
        val data = this.userList[position]
        val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)
        if (holder != null) {
            holder.tvUserName.text = data.name
            holder.tvUserPhone.text = data.phone
            holder.tvCreateDate.text = format.format(data.createDate)
            holder.itemView.setOnClickListener { onUserListListener.onItemClick(data) }
        }
    }

    override fun getItemCount(): Int {
        return this.userList.size
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): UserListViewHolder {
        val view = LayoutInflater.from(parent?.context).inflate(R.layout.activity_user_item, null, false)
        return UserListViewHolder(view)
    }

    /**
     * 用户 view holder
     */
    class UserListViewHolder constructor(itemview: View) : RecyclerView.ViewHolder(itemview) {
        val tvUserName = itemview.findViewById<AppCompatTextView>(R.id.tvUserName)
        val tvUserPhone = itemview.findViewById<AppCompatTextView>(R.id.tvUserPhone)
        val tvCreateDate = itemview.findViewById<AppCompatTextView>(R.id.tvCreateDate)
    }

    /**
     * 点击事件
     */
    interface OnUserListListener {
        fun onItemClick(user: UserTable)
    }
}
